package com.situ.blog.dao.impl;

import com.situ.blog.dao.IBlogTypeDao;
import com.situ.blog.pojo.entity.BlogType;
import com.situ.blog.pojo.query.BlogTypeQuery;
import com.situ.blog.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class BlogTypeDaoImpl implements IBlogTypeDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<BlogType> selectByPage(BlogTypeQuery blogTypeQuery) {

        String sql = "select * from blog_type where 1=1";

        List<Object> queryList = new ArrayList<>();
        String queryName = blogTypeQuery.getName();
        if (queryName != null && !queryName.equals("")){
            sql += " and name like ?";
            queryList.add("%" + queryName + "%");
        }

        sql += " limit ?,?";
        int offset = (blogTypeQuery.getPage() - 1)*blogTypeQuery.getLimit();
        queryList.add(offset);
        queryList.add(blogTypeQuery.getLimit());

        List<BlogType> list = template.query(sql,
                new BeanPropertyRowMapper<>(BlogType.class),queryList.toArray());

        return list;
    }

    @Override
    public int selectTotalCount(BlogTypeQuery blogTypeQuery) {

        String sql = "select count(*) from blog_type where 1=1";
        List<Object> queryList = new ArrayList<>();
        String queryName = blogTypeQuery.getName();
        if (queryName != null && !queryName.equals("")){
            sql += " and name like ?";
            queryList.add("%" + queryName + "%");
        }

        return template.queryForObject(sql,Integer.class,queryList.toArray());
    }

    @Override
    public void deleteById(int id) {
        template.update("delete from blog_type where id=?",id);
    }

    @Override
    public void add(BlogType blogType) {
        template.update("insert into blog_type(name) values(?)",blogType.getName());
    }

    @Override
    public BlogType seleteById(int id) {

        return template.queryForObject("select * from blog_type where id=?",
                new BeanPropertyRowMapper<>(BlogType.class),id);
    }

    @Override
    public void update(BlogType blogType) {
        template.update("update blog_type set name=? where id=?",
                blogType.getName(),blogType.getId());
    }

    @Override
    public List<BlogType> selectAll() {

        return template.query("select * from blog_type",
                new BeanPropertyRowMapper<>(BlogType.class));
    }
}
